package org.example.strategy;

import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Hint分片策略
 * @author shenguangyang
 */
public class CustomDbHintShardingAlgorithm implements HintShardingAlgorithm<Long> {
    /**
     * @param dataSourceNames 数据源集合
     *                        在分库时值为所有分库的集合 databaseNames
     *                        在分表时为对应分片库中所有分片表的集合 tablesNames
     * @param hintShardingValue 分片属性, 包括
     *                          logicTableName: 逻辑表
     *                          columnName: 分片键(字段), hit策略此处为空
     *                          value: 之前都是从SQl中解析出的分片键的值, 用于取模判断HintShardingAlgorithm不再
     *                          从SQL解析中获取值, 而是直接通过hintManager.addTableShardingValue("product_order", 1) 参数指定
     */
    @Override
    public Collection<String> doSharding(Collection<String> dataSourceNames, HintShardingValue<Long> hintShardingValue) {
        Collection<String> result = new ArrayList<>();
        for (String dbName : dataSourceNames) {
            for (Long shardingValue : hintShardingValue.getValues()) {
                String value = shardingValue % dataSourceNames.size() + "";
                if (dbName.endsWith(value)) {
                    result.add(dbName);
                }
            }
        }
        return result;
    }
}
